package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.PayConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.Course;
import cn.itsource.ymcc.domain.CourseUserLearn;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.mapper.CourseMapper;
import cn.itsource.ymcc.mapper.CourseUserLearnMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
@RocketMQMessageListener(consumerGroup = "service-updateCourseUserLearn-consumer",
        //Topic
        topic = PayConstants.MQ_TOPIC_PAYORDER_PAYORDER,
         //TAGS
        selectorExpression = PayConstants.MQ_TAGS_PAYORDER_PAYORDER
)
@Slf4j
public class CourseConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private CourseUserLearnMapper courseUserLearnMapper;

    @Autowired
    private CourseMapper courseMapper;
    @Override
    public void onMessage(MessageExt message) {

        try {
            byte[] body = message.getBody();
            String bodyStr = new String(body, Constants.UTF8);
            JSONObject jsonObject = JSONObject.parseObject(bodyStr);
            //将购买记录添加至user_learn
            String courseIds = jsonObject.get("courseId").toString();
            String[] split = courseIds.split(RConst.Str.COMMA);
            List<Course> courses = courseMapper.selectBatchIds(Arrays.asList(split));
            for (Course cours : courses) {
                CourseUserLearn courseUserLearn = new CourseUserLearn();
                courseUserLearn.setCourseId(cours.getId());
                courseUserLearn.setCourseOrderNo(jsonObject.get("orderNo").toString());
                courseUserLearn.setCreateTime(new Date());
                courseUserLearn.setStartTime(cours.getStartTime());
                courseUserLearn.setEndTime(cours.getEndTime());
                courseUserLearn.setState(RConst.Num.INT_0);
                courseUserLearn.setLoginId(Long.valueOf(jsonObject.get("userId").toString()));
                courseUserLearnMapper.insert(courseUserLearn);
            }
            log.info("用户购买记录持久化成功");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("用户购买记录失败");
        }
    }
}